import { Form, Input, Modal, Select, TreeSelect } from 'antd';
import { useImperativeHandle, useState } from 'react';

import deptsApi from '@/api/deptsApi';
import usersApi from '@/api/usersApi';
import { message } from '@/components/AntdGlobal';
import type { IDept, IUser } from '@/types/api';
import type { IAction, IModalProp } from '@/types/modal';

const CreateDept = (props: IModalProp<IDept.EditParams | { parentId: string }>) => {
    /* 数据管理 ---------------------------------------------------*/
    const [visible, setVisible] = useState(false);
    const [action, setAction] = useState<IAction>('create');
    const [form] = Form.useForm();
    const [deptList, setDeptList] = useState<IDept.DeptItem[]>([]);
    const [userList, setUserList] = useState<IUser.UserItem[]>([]);

    /* 函数定义 ---------------------------------------------------*/
    /**暴露子组件open方法，供父组件中调用props.mRef?.openModal()方法
     */
    useImperativeHandle(props.mRef, () => {
        return {
            openModal
        };
    });

    /**弹框显示
     * @param action 类型
     * @param data 数据
     */
    const openModal = async (action: IAction, data?: IDept.EditParams | { parentId: string }) => {
        setAction(action);
        setVisible(true);
        // 数据时效性，每次打开弹窗时重新获取数据
        await Promise.all([getAllUserList(), getDeptList()]);
        // 新增 or 编辑，表单赋值
        if (data && (action === 'create' || action === 'edit')) {
            form.setFieldsValue({ ...data });
        }
    };

    /**获取部门列表
     */
    const getDeptList = async () => {
        const { data } = await deptsApi.getDeptsList();
        setDeptList(data);
    };

    /**获取用户列表
     */
    const getAllUserList = async () => {
        const { data } = await usersApi.getAllUserList();
        setUserList(data);
    };

    /**表单提交
     */
    const handleSubmit = async () => {
        try {
            const valid = await form.validateFields();
            if (valid) {
                const values = form.getFieldsValue();
                if (action === 'create') {
                    await deptsApi.createDept(values);
                    message.success('创建成功');
                } else if (action === 'edit') {
                    await deptsApi.editDept(values);
                    message.success('修改成功');
                }
                // 关闭弹窗，重置表单数据
                handleCancel();
                // 父组件更新列表
                props.update();
            }
        } catch (error) {
            console.error(error);
        }
    };

    /**取消操作
     */
    const handleCancel = () => {
        setVisible(false);
        // 重置表单时机：退出时重置 优于 打开时判断重置
        form.resetFields();
    };

    return (
        <Modal
            title={action === 'create' ? '创建部门' : '编辑部门'}
            width={800}
            open={visible}
            okText="确定"
            cancelText="取消"
            onOk={handleSubmit}
            onCancel={handleCancel}
        >
            <Form
                form={form}
                labelCol={{
                    span: 4
                }}
                labelAlign="right"
            >
                {/* 隐藏提交项,edit时提交 */}
                <Form.Item
                    name="deptId"
                    hidden
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="上级部门"
                    name="parentId"
                >
                    <TreeSelect
                        placeholder="请选择上级部门"
                        allowClear
                        treeDefaultExpandAll
                        fieldNames={{ label: 'deptName', value: 'deptId' }}
                        treeData={deptList}
                        disabled={action === 'edit' && !form.getFieldValue('parentId')}
                    />
                </Form.Item>
                <Form.Item
                    label="部门名称"
                    name="deptName"
                    rules={[{ required: true, message: '请输入部门名称' }]}
                >
                    <Input placeholder="请输入部门名称" />
                </Form.Item>
                <Form.Item
                    label="负责人"
                    name="userName"
                    rules={[{ required: true, message: '请选择负责人' }]}
                >
                    <Select>
                        {userList.map((item) => {
                            return (
                                <Select.Option
                                    value={item.userId}
                                    key={item.userId}
                                >
                                    {item.userName}
                                </Select.Option>
                            );
                        })}
                    </Select>
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default CreateDept;
